<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .show {
        display: block;
    }

    .hide {
        display: none;
    }
</style>

<body>
    <div class="form">
        <div>
            <span>城市名称:</span> <input id="city" type="text">
        </div>
        <div>
            <span>空气质量指数:</span> <input id="air" type="text">
        </div>
        <div>
            <button type="button" id="addBtn">确认添加</button>
        </div>
    </div>
    <table >
        <thead id="dataHead">
            <tr>
                <th>城市</th>
                <th>空气质量</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id='dataBody'></tbody>
    </table>
</body>
<script>
    var city = document.getElementById('city');
    var air = document.getElementById('air');
    var addBtn = document.getElementById('addBtn');
    var dataHead = document.getElementById('dataHead');
    var dataBody = document.getElementById('dataBody');
    var data = {
        city: '',
        air: '',
    }
    Object.keys(data).forEach((item) => {
        this.observe(data, item, data[item]);
    });
    city.onchange = function (e) {
        data.city = e.target.value;
    }
    air.onchange = function (e) {
        data.air = e.target.value;
    }
    addBtn.onclick = function (e) {
        if (data.city && data.air) {
            dataBody.appendChild(createData());
            remove();
        } else {
            alert('city或air不能为空')
        }
    }

    function createData() {
        var dataBody = `<tr class='dataItem'>
                   <td>${data.city}</td>
                   <td>${data.air}</td>
                   <td><button class='remove'>删除</button></td>
                </tr>`;
        var table = document.createElement('tbody');
        table.innerHTML = dataBody;
        data.city = '';
        data.air = '';
        city.value = '';
        air.value = '';
        return table.firstChild;
    }

    function remove() {
        var removes = [...document.getElementsByClassName('remove')];
        var dataItems = [...document.getElementsByClassName('dataItem')]
        console.log(removes);
        removes.forEach((item,index) => {
            console.log(item);
            item.addEventListener('click', function(){
                dataItems[index].remove();
            })
        })
    }

    function observe(data, key, value) {
        Object.defineProperty(data, key, {
            get() {
                return value;
            },
            set(newVal) {
                value = newVal;
            }
        });
    }
</script>

</html>